import Pyro4
import ctypes
from ctypes import Structure
from ctypes import byref
import ctypes.wintypes as wintypes

SE_PRIVILEGE_ENABLED = 2
SE_SHUTDOWN_NAME = 'SeShutdownPrivilege'
TOKEN_ALL_ACCESS = 0xf00ff
TOKEN_ADJUST_PRIVILEGES = 0x20
host = None  #: it means local machine.

class LUID(Structure):
  _fields_ = [("LowPart", wintypes.DWORD),
              ("HighPart", wintypes.LONG)]

class LUID_AND_ATTRIBUTES(Structure):
  _fields_ = [("Luid", LUID),
              ("Attributes", wintypes.DWORD)]  

class TOKEN_PRIVILEGES(Structure):
  _fields_ = [("PrivilegeCount", wintypes.DWORD),
              ("Privileges", LUID_AND_ATTRIBUTES)]  


def shutdown(msg, timeout, force=True, reboot=True):
  advapi32 = ctypes.windll.advapi32
  kernel32 = ctypes.windll.kernel32

  luid = LUID()
  if not advapi32.LookupPrivilegeValueA(None, SE_SHUTDOWN_NAME, byref(luid)):
    print 'LookupPrivilegeValueA failed.'

  attr = LUID_AND_ATTRIBUTES(luid, SE_PRIVILEGE_ENABLED)
  privilegeCount = 1
  tokenPrivileges = TOKEN_PRIVILEGES(privilegeCount, attr)

  p = kernel32.GetCurrentProcess()
  hToken = wintypes.HANDLE()
  if not advapi32.OpenProcessToken(p, TOKEN_ADJUST_PRIVILEGES, byref(hToken)):
    print 'OpenProcessToken failed.'
    return False
  if not advapi32.AdjustTokenPrivileges(hToken, False, byref(tokenPrivileges), None, None, None):
    print 'AdjustTokenPrivileges failed.'
    return False
  if not advapi32.InitiateSystemShutdownA(host, msg, timeout, force, reboot):
    print 'InitiateSystemShutdownA failed.'
    return False
  return True

class AdministrationService(object):
    def shutdown(self):
        shutdown('This computer is about to shutdown...', 10)
        pass
    def restart(self):
        pass
    def listapp(self):
        pass
    def killapp(self,pid=None,image=None):
        pass
    def startapp(self,image):
        pass

def main():
   admsrv=AdministrationService()
   Pyro4.Daemon.serveSimple(
      {
	    billserver: "admsrv.damarnet"
	  },
	  ns=False,host='10.0.0.13',port=2012)


if __name__=="__main__":
  main()